<?php


namespace addons\csmitsm\controller;

use addons\csmitsm\library\sdnode\xstack\utils\XsJsonUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcConfigUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcflowToMdmUtils;
use addons\csmitsm\library\xcore\xcflow\base\XcformAAddonsController;
use addons\csmitsm\library\xcore\xcflow\utils\XcflowGraphDataUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformDataUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformFieldsUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcTransactionUtils;

class XcFlow extends XcformAAddonsController
{
    protected $staticFieldsJsonString = null;

    public function xinit()
    {
        $this->xcformDao = new \app\admin\model\csmitsm\Xcflow();

        $this->xcformFieldDao = new \app\admin\model\csmitsm\Xcflowfield();
        $this->xcformidFieldname = "xcflow_id";

        $this->staticFieldsJsonString = XcConfigUtils::xpconfig("xcflow.xcflow.staticFieldsJsonString");
    }

    protected function _publishXcForm_alertColumn($xcform, $field, $fieldcode, $columnType, $fieldTitle)
    {
        if ($xcform->mdmtabletype == 'create_table' && !empty($xcform->mdmtablename)) {
            XcformDataUtils::alertTableField($field->publishtype, $xcform->mdmtablename, $fieldcode, $columnType, $fieldTitle);
            $mdmfieldjsObj = XcflowToMdmUtils::generateCreateTableMdmfieldjsonFromXcflowTable($xcform);
            $xcform->save(['mdmfieldjson' => XsJsonUtils::jsonToString($mdmfieldjsObj)]);
        }
    }

    public function getInitXcflowJsonString(){
        $xcflowjson = XcConfigUtils::xpconfig("xcflow.xcflow.staticXcflowJsonString");
        $this->success(null, [
            "xcflowjson" => $xcflowjson,
        ]);
    }

    public function getXcFlowJsonForPhagh()
    {
        $xcflow_id = XcRequestUtils::get("xcflow_id", true);
        $xcflowjsonRow = $this->_getLastXcFlowJsonRow($xcflow_id);

        $xcflow = XcDaoUtils::getRowById(new \app\admin\model\csmitsm\Xcflow(), $xcflow_id);
        $xcflowFields = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($xcflow);


        // 当前xcflowjson是否生效,Y/N;
        $iseffect = null;
        // 如果XcFlowJson表有草稿记录则是N, 否则为Y
        $xcflowjson = null;
        if (true) {
            if ($xcflowjsonRow != null && $xcflowjsonRow->iseffect == 'N') {
                $xcflowjson = $xcflowjsonRow->xcflowjson;
                $iseffect = "N";
            } else {
                $xcflowjson = $xcflow->xcflowjson;
                $iseffect = "Y";
            }

            if (empty($xcflowjson)) {
                $xcflowjson = XcConfigUtils::xpconfig("xcflow.xcflow.staticXcflowJsonString");
            }
        }

        $roleList = null;
        if (true) {
            $roleList = XcDaoUtils::getListBySql(new \app\admin\model\AuthGroup(), []);
        }

        $this->success(null, [
            "xcflowjson" => $xcflowjson,
            "xcflowFields" => $xcflowFields,
            "iseffect" => $iseffect,
            "roleList" => $roleList
        ]);
    }

    public function saveXcFlowJsonForPhagh()
    {
        $xcflow_id = XcRequestUtils::post("xcflow_id", true);
        $xcflowjson = XcRequestUtils::post("xcflowjson", true);

        // 如果XcFlowJson表有draft的版本数据则更新，否则为新增
        $dao = new \app\admin\model\csmitsm\Xcflowjson();
        $xcflowjsonRow = $this->_getLastXcFlowJsonRow($xcflow_id);
        if ($xcflowjsonRow == null || $xcflowjsonRow->iseffect == 'Y') {
            $dao->create([
                "xcflow_id" => $xcflow_id,
                "name" => date('Y-m-d H:i:s'),
                "xcflowjson" => $xcflowjson,
                "iseffect" => 'N',
                'weigh' => 0
            ]);
        } else {
            $xcflowjsonRow->save([
                "name" => date('Y-m-d H:i:s'),
                "xcflowjson" => $xcflowjson,
                "iseffect" => 'N'
            ]);
        }
        $this->success();
    }

    public function submitXcFlowJsonForPhagh()
    {
        $xcflow_id = XcRequestUtils::post("xcflow_id", true);
        $xcflowjson = XcRequestUtils::post("xcflowjson", true);


        XcTransactionUtils::service(function () use ($xcflow_id, $xcflowjson) {
            $xcflowjson = XcflowGraphDataUtils::appendWeighToXcflowjson($xcflowjson);

            // 如果tXcFlowJson表有draft的版本数据则更新，否则为新增
            $dao = new \app\admin\model\csmitsm\Xcflowjson();
            $xcflowjsonRow = $this->_getLastXcFlowJsonRow($xcflow_id);
            if ($xcflowjsonRow == null || $xcflowjsonRow->iseffect == 'Y') {
                $xcflowjsonRow = $dao->create([
                    "xcflow_id" => $xcflow_id,
                    "name" => date('Y-m-d H:i:s'),
                    "xcflowjson" => $xcflowjson,
                    "iseffect" => 'Y'
                ]);
            } else {
                $xcflowjsonRow->save([
                    "name" => date('Y-m-d H:i:s'),
                    "xcflowjson" => $xcflowjson,
                    "iseffect" => 'Y'
                ]);
            }

            // 蒋json数据写入到xcFlow表中
            $xcflowRow = XcDaoUtils::getRowById(new \app\admin\model\csmitsm\Xcflow(), $xcflow_id);
            $xcflowRow->save([
                'xcflowjson' => $xcflowjsonRow->xcflowjson,
                'xcflowjson_id' => $xcflowjsonRow->id,
            ]);

            // sync to fa_csmitsm_xcflow_rynode
            if (true) {
                $xcflowjsonObj = json_decode($xcflowjsonRow->xcflowjson, true); 
                $toSyncModels = [];
                foreach ($xcflowjsonObj['fstatusList'] as $status) {
                    $toSyncModels[] = [
                        "xcflow_id" => $xcflowRow->id,
                        "fstatuscode" => $status['code'],
                        "fstatusname" => $status['name'],
                        "weigh" => $status['weigh'],
                    ];
                }
                XcDaoUtils::createOrUpdateOrDeleteDatas(
                    new \app\admin\model\csmitsm\XcflowRystatus(),
                    $toSyncModels,
                    ["xcflow_id", "fstatuscode"],
                    "id",
                    ["xcflow_id", "fstatuscode", "fstatusname", "weigh"],
                    [["xcflow_id", "=", $xcflowRow->id]]
                );
            }
        });

        $this->success();
    }

    private function _getLastXcFlowJsonRow($xcflow_id)
    {
        return XcDaoUtils::getRowBySql(new \app\admin\model\csmitsm\Xcflowjson(), [
            ["xcflow_id", "=", $xcflow_id]
        ]);
    }
}
